<template>
  <el-dialog
    :class="currentDialog.current"
    :title="title"
    :visible.sync="currentDialog.showDialog"
    :before-close="handleClose"
    :close-on-click-modal="closeModal"
  >
    <!-- 书币充值弹窗 -->
    <div class="coins-recharge" v-if="currentDialog.current === 'coins'">
      <ul class="card-list">
        <li
          v-for="item of list"
          :key="item.rechargeId || item.vipId"
          :class="{
            dot: item.characterCorner ? true : false,
            active: item.rechargeId
              ? item.rechargeId == currentCard.rechargeId
              : item.vipId == currentCard.vipId,
          }"
          :li-content="item.characterCorner"
          @click="selectCard(item)"
        >
          <h3
            class="ellipsis"
            :title-content="item.conversionCoin ? 'COINS' : ''"
            v-text="item.conversionCoin || item.vipNameEns"
          ></h3>
          <p
            class="desc ellipsis-two"
            :add-content="item.giveCoin ? '+' : ''"
            :desc-content="item.giveCoin ? 'COINS' : ''"
            v-text="item.giveCoin || item.text"
          ></p>
          <div
            class="price"
            v-text="'us$ ' + (item.rechargeSum || item.price)"
            :price-content="item.linePrice ? `us$ ${item.linePrice}` : ''"
          ></div>
        </li>
      </ul>
      <pay-list
        :payListStyle="'coins-pay-list'"
        :currentCard="currentCard"
        @recharge="recharge"
      ></pay-list>
    </div>
    <!-- 会员充值弹窗 -->
    <div
      class="premium-recharge"
      v-else-if="currentDialog.current === 'premium'"
    >
      <ul class="card-list">
        <li
          v-for="item of list"
          :key="item.vipId"
          :class="{
            dot: item.characterCorner ? true : false,
            active: item.vipId == currentCard.vipId,
          }"
          :li-content="item.characterCorner"
          @click="selectCard(item)"
        >
          <span
            class="desc"
            v-text="item.vipNameEns"
            :desc-content="item.text"
          ></span>
          <span
            class="price"
            v-text="'us$' + item.price"
            :price-content="'us$' + item.linePrice"
          ></span>
        </li>
      </ul>
      <pay-list
        :payListStyle="'premium-pay-list'"
        :currentCard="currentCard"
        @recharge="recharge"
      ></pay-list>
    </div>
    <!-- 登录 -->
    <div class="login-box" v-else-if="currentDialog.current === 'login'">
      <div class="head">
        <h2 class="title">Log in to FishNovel</h2>
        <span class="close-icon" @click="handleClose">
          <svg-icon icon-class="loginCloseIcon"></svg-icon>
        </span>
      </div>
      <div class="content" v-if="loginMode === 6">
        <!-- <el-form :model="form" :rules="rules" ref="form">
          <el-form-item prop="email">
            <h3 class="label">Email</h3>
            <el-input
              type="email"
              v-model="form.email"
              placeholder="Please enter email address."
            ></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <h3 class="label">Verify Code</h3>
            <el-input
              v-model="form.email"
              placeholder="Please enter verification code."
              @keyup.13="login(6)"
            ></el-input>
          </el-form-item>
        </el-form> -->
        <div class="text">
          <h3 class="label">Email</h3>
          <!-- :state="emailStatus" -->
          <input
            ref="email-input"
            placeholder="Please enter email address."
            type="email"
            @blur="hideTips('email')"
            v-model="form.email"
          />
          <span id="email_hint" class="text_hint"></span>
        </div>
        <div class="text">
          <h3 class="label">Verify Code</h3>
          <div class="code-input-box">
            <input
              ref="code-input"
              placeholder="Please enter verification code."
              type="text"
              @blur="hideTips('code')"
              @keyup.13="login(6)"
              v-model="form.code"
            />
            <span
              :class="timeText === '' ? 'getCode' : 'disabled'"
              @click="getCode"
              v-text="codeText + this.timeText"
            ></span>
          </div>
          <span id="code_hint" class="text_hint"></span>
        </div>
      </div>
      <div class="submit">
        <el-button @click="login(loginMode)">Log in</el-button>
      </div>
      <div class="foot">
        <div class="toggle-login">
          <span class="logo-facebook" @click="otherLogin(8)">
            <svg-icon icon-class="logoFacebook"></svg-icon>
          </span>
          <span id="logo-google" @click="otherLogin(7)">
            <svg-icon icon-class="logoGoogle"></svg-icon>
          </span>
          <!-- <span class="logo-apple" @click="otherLogin(10)">
            <svg-icon icon-class="logoApple"></svg-icon>
          </span> -->
        </div>
        <p class="login-describe">
          Unregistered FishNovel accounts will be automatically registered upon
          login
        </p>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import PayList from "components/common/PayList/Index";
import { mapMutations, mapGetters } from "vuex";
export default {
  data() {
    return {
      list: [], //recharge列表
      currentCard: {}, //当前选中的recharge卡片
      loginMode: 6, // 邮箱:6  Facebook:8 GoogleOn:7
      form: {
        email: "",
        code: "",
      },
      googleUser: {},
      // rules: {
      //   email: [
      //     { required: true, message: 'Email is required.', trigger: 'blur' },
      //     { type: 'email', message: 'That is not a valid email address.', trigger: ['blur', 'change'] }
      //   ],
      //   code: [
      //     { required: true, message: 'Verification code is required.', trigger: 'blur' },
      //     { type: 'email', message: 'That is not a valid email address.', trigger: ['blur', 'change'] }
      //   ]
      // },
      codeText: "GET", //获取验证码文字
      timeText: "", //倒计时
      username: "", //用户名
      openid: null,
    };
  },
  props: {},
  components: {
    PayList,
  },
  computed: {
    ...mapGetters(["currentDialog"]),
    title() {
      if (this.currentDialog.current === "coins") {
        return "Coins Recharge";
      } else if (this.currentDialog.current === "premium") {
        return "Premium";
      } else if (this.currentDialog.current === "login") {
        return "Log in to FishNovel";
      } else {
        return "FishNovel";
      }
    },
    closeModal() {
      return this.currentDialog.current !== "login";
    },
  },
  watch: {},
  created() {
    if (this.currentDialog.current === "coins") {
      this.getCoinRecharge();
    } else if (this.currentDialog.current === "premium") {
      this.getVipPremium();
    }
    this.startApp();
  },
  mounted() {},
  methods: {
    ...mapMutations({
      setBalance: "SET_BALANCE",
      setLoginInfo: "SET_LOGININFO",
      setCurrentDialog: "SET_CURRENT_DIALOG",
    }),
    // async onLoadSDK(str){
    //   let that = this;
    //   if (str === "google") {
    //     let script = document.createElement("script");
    //     script.type = "text/javascript";
    //     script.src = "https://apis.google.com/js/api:client.js";
    //     document.head.appendChild(script);
    //     script.onload=script.onreadystatechange=function(){
    //       if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
    //         that.startApp(str);
    //       }
    //       script.onload=script.onreadystatechange=null;
    //     }
    //   }
    // },
    googleIni() {
      window.gapi.load("auth2", () => {
        // Retrieve the singleton for the GoogleAuth library and set up the client.
        this.auth2 = window.gapi.auth2.init({
          client_id:
            "139301213659-qqqlitnpvv0sagl7m96agrfbd9lujqs0.apps.googleusercontent.com", //客户端ID
          cookiepolicy: "single_host_origin",
          scope: "profile", //可以请求除了默认的'profile' and 'email'之外的数据
        });
      });
    },
    toDetail(id) {
      this.$router.push({
        name: "bookDetail",
        params: { id },
      });
    },
    // 关闭回调
    handleClose() {
      this.setCurrentDialog(null);
      // if (this.currentDialog.current === "login") {
      //   this.init();
      // }
    },
    //子组件 充值完成调用
    recharge(res) {
      this.getUserBalanceAndVip();
      if (res.isFirstRecharge === 1) {
        this.getCoinRecharge();
      }
    },
    // 当前选中套餐
    selectCard(item) {
      // console.log(item);
      this.currentCard = item;
    },
    // 获取用户余额信息
    async getUserBalanceAndVip() {
      let res = await this.$api.home.getUserBalanceAndVip({});
      if (res.code === 1) {
        this.setBalance(res.source);
      }
    },
    // 查询书币充值和连续充值套餐列表
    async getCoinRecharge() {
      let res = await this.$api.home.getCoinRecharge({});
      if (res.code === 1) {
        this.list = res.source.sort(this.utils.compareSort("sort"));
        this.currentCard = this.list[0];
      }
    },
    // 获取所有premium会员相关配置信息
    async getVipPremium() {
      let res = await this.$api.home.getVipPremium({});
      console.log(res);
      if (res.code === 1) {
        this.list = res.source;
        this.currentCard = this.list[0];
      }
    },
    // 登录相关
    // 获取验证码
    async getCode() {
      if (this.checkEmpty("email")) {
        if (this.hideTips("email")) {
          let time = 60;
          this.codeText = "Reacquire ";
          this.timeText = time + "S";
          let sendTimer = setInterval(() => {
            time--;
            this.timeText = time + "S";
            if (time < 0) {
              clearInterval(sendTimer);
              this.codeText = "GET";
              this.timeText = "";
            }
          }, 1000);
          let params = {
            emailUrl: this.form.email,
          };
          let res = await this.$api.login.code(params);
          if (res.code === 200031) {
            // 发送过于频繁
            document.getElementById("email_hint").innerHTML =
              "Please try again later";
          } else if (res.code === 200030) {
            // 未进行实名认证
            document.getElementById("email_hint").innerHTML =
              "The real-name authentication is not performed";
          }
          //  else {
          //   // 其他 -这不是一个有效的邮箱
          //   document.getElementById("email_hint").innerHTML =
          //     "That is not a valid email address.";
          // }
        }
      }
    },
    otherLogin(mode) {
      // Facebook登录
      if (mode === 8) {
        window.FB.getLoginStatus((response) => {
          // 登入狀態 - 已登入
          if (response.status === "connected") {
            // 獲取用戶個人資料
            this.getProfile(mode);
          } else {
            // 登入狀態 - 未登入
            // 用戶登入(確認授權)
            window.FB.login(
              () => {
                // 獲取用戶個人資料
                this.getProfile(mode);
              },
              // 授權 - 個人資料&Email
              { scope: "public_profile,email" }
            );
          }
        });
      } else if (mode === 7) {
        // this.onLoadSDK("google")
        this.getProfile(mode);
      }
    },
    async login(mode, params) {
      // 邮箱登录
      if (mode === 6) {
        let isEmpty = this.checkEmpty("email") && this.hideTips("email");
        if (isEmpty) {
          if (this.checkEmpty("code")) {
            params = {
              code: this.form.code,
              openid: this.form.email,
              type: mode,
            };
          }
        }
      } else if (mode === 7) {
        // Google登录
        // params = {
        //   openid: this.googleId,
        //   headImgUrl: this.googleImg,
        //   nickname: this.googleusername,
        //   type: this.is_type,
        // };
      } else if (mode === 8) {
        // Facebook登录
        // params = {
        //   openid: this.openid,
        //   nickname: this.username,
        //   type: 8,
        // };
      }
      if (params) {
        let res = await this.$api.login.login(params);
        if (res.code === 1) {
          // this.setShowPopup(false);
          this.setCurrentDialog(null);
          this.setLoginInfo(res.source);
          await this.getUserBalanceAndVip();
          // this.reload();
          // 用户数据日志
          // setTimeout(() => {
          this.$api.logger.user_analysis({ logType: 1 });
          // }, 1314);
        } else if (res.code === 200015) {
          document.getElementById("code_hint").innerHTML =
            "That is not a valid verification code.";
        } else {
          // Login failed, please try again.
        }
      }
    },
    // 获取个人资料
    getProfile(mode) {
      if (mode === 8) {
        window.FB.api("/me?fields=name,id,email", (res) => {
          if (res.id) {
            // this.username = res.name;
            // this.openid = res.id;
            let params = {
              openid: res.id,
              nickname: res.name,
              type: 8,
            };
            this.login(8, params);
          }
        });
      } else if (mode === 7) {
        // Google登录
        let element = document.getElementById("logo-google");
        this.auth2.attachClickHandler(
          element,
          {},
          (googleUser) => {
            var profile = this.auth2.currentUser.get().getBasicProfile();
            console.log("token: " + googleUser.wc.id_token);
            console.log("ID: " + profile.getId());
            console.log("Full Name: " + profile.getName());
            console.log("Given Name: " + profile.getGivenName());
            // console.log('Family Name: ' + profile.getFamilyName());
            console.log("Image URL: " + profile.getImageUrl());
            console.log("Email: " + profile.getEmail());
            let params = {
              openid: profile.getId(),
              headImgUrl: profile.getImageUrl(),
              nickname: profile.getName(),
              type: 7,
              // nickname: profile.getName(),
              // email: profile.getEmail(),
              // id_token: googleUser.wc.id_token,
              // avatar: profile.getImageUrl(),
              // google_id: profile.getId(),
            };
            this.login(7, params);
            console.log(params);
          },
          function (error) {
            console.log(JSON.stringify(error, undefined, 2));
          }
        );
      }
    },
    // 验证邮箱/验证码是否为空 提示
    checkEmpty(text) {
      if (text === "email") {
        let span = document.getElementById("email_hint");
        let input = this.$refs["email-input"];
        if (this.form.email) {
          span.innerHTML = "";
          input.classList.remove("error");
          return true;
        } else {
          span.innerHTML = "Email is required.";
          input.classList.add("error");
          return false;
        }
      } else if (text === "code") {
        let span = document.getElementById("code_hint");
        let input = this.$refs["code-input"];
        if (this.form.code) {
          span.innerHTML = "";
          input.classList.remove("error");
          return true;
        } else {
          span.innerHTML = "Verification code is required.";
          input.classList.add("error");
          return false;
        }
      }
    },
    // 邮箱焦点离开事件 - 判断邮箱格式
    hideTips(text) {
      if (text === "email") {
        let span = document.getElementById("email_hint");
        let input = this.$refs["email-input"];
        if (this.form.email) {
          if (this.checkEmail(this.form.email)) {
            span.innerHTML = "";
            input.classList.remove("error");
            return true;
          } else {
            span.innerHTML = "That is not a valid email address.";
            input.classList.add("error");
            return false;
          }
        } else {
          span.innerHTML = "";
          input.classList.remove("error");
          return false;
        }
      } else if (text === "code") {
        let span = document.getElementById("code_hint");
        // 验证码错误提示
        if (this.form.code) {
          return true;
        } else {
          span.innerHTML = "";
          return false;
        }
      }
    },
    // 校验邮箱
    checkEmail(strEmail) {
      var emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (emailReg.test(strEmail)) {
        return true;
      } else {
        return false;
      }
    },
    // form初始化
    // init() {
    //   this.form = {
    //     email: "",
    //     code: "",
    //   };
    //   this.loginMode = 6;
    //   document.getElementById("email_hint").innerHTML = "";
    //   document.getElementById("code_hint").innerHTML = "";
    // },
  },
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
  &.coins,
  &.premium {
    ::v-deep .el-dialog {
      width: 600px;
      margin-top: 73px !important;
      box-shadow: 0px 0px 8px 2px rgba(35, 28, 28, 0.05);
      border-radius: 16px;
      .el-dialog__header {
        padding: 28px 32px 22px;
        .el-dialog__title {
          font-size: 24px;
          font-family: Poppins-SemiBold, Poppins;
          font-weight: 600;
          color: #000000;
          line-height: 40px;
        }
        .el-dialog__close {
          line-height: 40px;
          color: #000;
          font-weight: bold;
        }
      }
      .el-dialog__body {
        padding: 0 32px;
        .coins-recharge {
          > ul.card-list {
            padding: 12px 0;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            li {
              width: 160px;
              height: 160px;
              margin: 14px 0;
              cursor: pointer;
              box-sizing: border-box;
              border-radius: 16px;
              position: relative;
              display: flex;
              text-align: center;
              flex-direction: column;
              border: 2px solid #eeeeee;
              h3 {
                font-size: 22px;
                word-break: keep-all;
                white-space: pre-wrap;
                padding: 32px 14px 0;
                font-family: Poppins-SemiBold, Poppins;
                color: #000000;
                line-height: 22px;
                &::after {
                  content: attr(title-content);
                  // font-weight: normal;
                  margin-left: 8px;
                  font-size: 16px;
                }
              }
              .desc {
                padding: 0 14px;
                line-height: 22px;
                font-size: 16px;
                font-family: PingFangSC-Medium, PingFang SC;
                color: #e86472;
                &::before {
                  content: attr(add-content);
                }
                &::after {
                  content: attr(desc-content);
                  margin-left: 6px;
                }
              }
              .price {
                width: 100%;
                margin-top: auto;
                box-sizing: border-box;
                padding: 0 10px;
                font-size: 22px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #e86472;
                line-height: 40px;
                background: #eeeeee;
                border-radius: 0px 0px 14px 14px;
              }
              &.active,
              &:hover {
                width: 167px;
                height: 167px;
                margin: 7px 0;
                border-color: #e86472;
                .price {
                  background: #fceff0;
                }
              }
              &.dot::after {
                content: attr(li-content);
                width: 84px;
                height: 36px;
                box-sizing: border-box;
                display: flex;
                justify-content: center;
                align-items: center;
                position: absolute;
                top: -18px;
                right: -2px;
                padding: 0 8px;
                font-size: 14px;
                font-family: PingFangSC-Medium, PingFang SC;
                color: #ffffff;
                font-weight: 500;
                background: #e86472;
                border-radius: 0px 16px 0px 16px;
              }
            }
          }
        }
        .premium-recharge {
          > ul.card-list {
            display: flex;
            flex-direction: column;
            > li {
              width: 100%;
              height: 104px;
              cursor: pointer;
              padding: 22px 28px;
              box-sizing: border-box;
              border-radius: 16px;
              border: 2px solid #eeeeee;
              margin: 14px 0;
              display: flex;
              justify-content: space-between;
              position: relative;
              &.dot::after {
                content: attr(li-content);
                height: 32px;
                position: absolute;
                top: -16px;
                right: -2px;
                padding: 0 14px;
                font-size: 14px;
                color: #ffffff;
                line-height: 32px;
                font-weight: 500;
                background: #e86472;
                font-family: PingFangSC-Medium, PingFang SC;
                border-radius: 0px 16px 0px 16px;
              }
              &.active {
                background: #fcf0df;
                border-color: #d4902f;
              }
              .desc {
                font-size: 18px;
                color: #333333;
                font-weight: 500;
                line-height: 29px;
                font-family: Poppins-Medium, Poppins;
                &::after {
                  content: attr(desc-content);
                  display: block;
                  margin-top: 5px;
                  font-size: 14px;
                  font-weight: 400;
                  color: #e86472;
                  line-height: 20px;
                  font-family: PingFangSC-Regular, PingFang SC;
                }
              }
              .price {
                font-size: 20px;
                font-weight: 500;
                color: #d4902f;
                line-height: 32px;
                text-align: right;
                font-family: Poppins-Medium, Poppins;
                &::after {
                  content: attr(price-content);
                  display: block;
                  margin-top: 3px;
                  color: #cccccc;
                  font-size: 14px;
                  line-height: 20px;
                  text-decoration: line-through;
                  font-family: Poppins-Medium, Poppins;
                }
              }
            }
          }
        }
        // 支付列表
        .pay-list {
          &::before {
            content: "Payment Method";
            display: block;
            font-size: 24px;
            font-weight: 600;
            font-family: Poppins-SemiBold, Poppins;
            color: #000000;
            line-height: 40px;
            margin-bottom: 34px;
          }
        }
      }
    }
  }
  &.login {
    ::v-deep .el-dialog {
      width: 548px;
      // margin-top: 73px !important;
      box-shadow: 0px 0px 8px 2px rgba(35, 28, 28, 0.05);
      border-radius: 16px;
      background: url(../../../assets/images/login-back.png);
      .el-dialog__header {
        display: none;
      }
      .el-dialog__body {
        padding: 0;
        // 登录相关
        .login-box {
          width: 100%;
          padding: 32px;
          position: relative;
          box-sizing: border-box;
          background-size: 100% 100%;
          background-repeat: no-repeat;
          display: flex;
          flex-direction: column;
          .head {
            text-align: center;
            > .title {
              font-size: 24px;
              font-family: Poppins-SemiBold, Poppins;
              font-weight: 600;
              color: #000000;
              line-height: 40px;
            }
            .close-icon {
              cursor: pointer;
              .svg-icon {
                width: 38px;
                height: 38px;
                position: absolute;
                top: 0;
                right: 0;
              }
            }
          }
          .content {
            padding: 16px 0;
            .text {
              margin: 16px 0;
              .label {
                color: #333;
                font-size: 18px;
                margin-bottom: 16px;
              }
              input {
                width: 100%;
                height: 48px;
                padding: 0 16px;
                box-sizing: border-box;
                font-size: 22px;
                border-radius: 8px;
                background: #f5f5f5;
                border: 1px solid #d5d5d5;
                &:focus {
                  outline: none;
                  border: 1px solid #f55651;
                }
                &.error {
                  border-color: #f55651;
                  box-shadow: 0px 0px 0px 4px #ffdbda;
                }
              }
              .code-input-box {
                position: relative;
                > span {
                  width: auto;
                  height: 48px;
                  cursor: pointer;
                  font-size: 22px;
                  font-weight: 500;
                  line-height: 48px;
                  padding: 0 18px;
                  display: block;
                  position: absolute;
                  top: 0;
                  right: 0;
                  font-family: PingFangSC-Medium, PingFang SC;
                  &.getCode {
                    color: #f55651;
                  }
                  &.disabled {
                    color: #a4a4a4;
                    pointer-events: none;
                  }
                }
              }
              .text_hint {
                height: 28px;
                margin-top: 6px;
                display: block;
                line-height: 28px;
                color: #f55651;
                font-family: PingFangSC-Regular, PingFang SC;
              }
            }
          }
          .submit {
            .el-button {
              width: 100%;
              height: 48px;
              margin: 8px 0 63px 0;
              font-size: 22px;
              font-weight: 600;
              color: #fff;
              border: none;
              border-radius: 8px;
              background: linear-gradient(90deg, #ee685a 0%, #e25177 100%);
            }
          }
          .foot {
            border-top: 2px solid #eeeeee;
            &::before {
              content: "OR";
              width: 86px;
              height: 20px;
              display: block;
              font-size: 22px;
              background: #fff;
              font-weight: 600;
              color: #333;
              text-align: center;
              margin: -12px auto;
            }
            .toggle-login {
              display: flex;
              justify-content: space-around;
              margin: 46px 0 36px 0;
              .svg-icon {
                width: 46px;
                height: 46px;
                cursor: pointer;
              }
            }
            .login-describe {
              text-align: center;
              color: #666666;
              line-height: 22px;
              word-break: keep-all;
              white-space: pre-wrap;
              font-family: PingFangSC-Regular, PingFang SC;
            }
          }
        }
      }
    }
  }
}
</style>
